/**
 * 音频处理工具函数
 */

// Blob转Base64
export const blobToBase64 = (blob: Blob): Promise<string> => {
  return new Promise((resolve, reject) => {
    console.log('blobToBase64 接收到的参数:', blob)
    console.log('参数类型:', typeof blob)
    console.log('是否为Blob实例:', blob instanceof Blob)
    
    if (!(blob instanceof Blob)) {
      reject(new Error('参数不是Blob类型'))
      return
    }
    
    const reader = new FileReader()
    reader.onload = () => resolve(reader.result as string)
    reader.onerror = reject
    reader.readAsDataURL(blob)
  })
}

// Base64转Blob
export const base64ToBlob = (base64: string, mimeType: string): Blob => {
  const byteCharacters = atob(base64.split(',')[1])
  const byteNumbers = new Array(byteCharacters.length)
  
  for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i)
  }
  
  const byteArray = new Uint8Array(byteNumbers)
  return new Blob([byteArray], { type: mimeType })
}

// 检查浏览器是否支持录音
export const checkAudioSupport = (): boolean => {
  return !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia)
}

// 获取音频设备权限
export const requestAudioPermission = async (): Promise<boolean> => {
  try {
    const stream = await navigator.mediaDevices.getUserMedia({ 
      audio: {
        sampleRate: 16000,
        channelCount: 1,
        echoCancellation: true,
        noiseSuppression: true
      }
    })
    
    // 立即停止流，只是检查权限
    stream.getTracks().forEach(track => track.stop())
    return true
  } catch (error) {
    console.error('获取音频权限失败:', error)
    return false
  }
}

// 格式化音频时长
export const formatDuration = (duration: number | undefined): string => {
  if (!duration) return '0:00'
  const minutes = Math.floor(duration / 60)
  const seconds = Math.floor(duration % 60)
  return `${minutes}:${seconds.toString().padStart(2, '0')}`
}

// 播放语音文件
export function playVoice(
  url: string, 
  onEnd?: () => void, 
  onError?: (error: any) => void,
  onTimeUpdate?: (currentTime: number, duration: number) => void
): HTMLAudioElement {
  const audio = new Audio(url)
  
  audio.addEventListener('loadeddata', () => {
    console.log('语音文件加载完成:', url)
    console.log('语音时长:', audio.duration, '秒')
  })
  
  audio.addEventListener('canplay', () => {
    console.log('语音可以播放:', url)
    audio.play().catch(error => {
      console.error('播放失败:', error)
      onError?.(error)
    })
  })
  
  audio.addEventListener('timeupdate', () => {
    onTimeUpdate?.(audio.currentTime, audio.duration)
  })
  
  audio.addEventListener('ended', () => {
    console.log('语音播放结束:', url)
    onEnd?.()
  })
  
  audio.addEventListener('error', (event) => {
    console.error('语音播放错误:', event)
    onError?.(event)
  })
  
  return audio
}

